package main

import (
	"io/ioutil"
	"os"
	"path/filepath"

	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/app"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/widget"
	"github.com/zhaocy/fyne-theme"
)

func main() {
	myApp := app.New()
	myApp.Settings().SetTheme(themex.Themex())
	myWin := myApp.NewWindow("tree")

	lb := widget.NewLabel("")

	//tree data
	treeData := map[string][]string{
		"":   {"体育", "美食"},
		"体育": {"羽毛球", "篮球", "跑步"},
		"美食": {"川菜", "粤菜"},
	}

	// 创建tree
	tree := widget.NewTreeWithStrings(treeData)
	// 打开所有分支
	// tree.OpenAllBranches()
	// 打开指定分支
	// tree.OpenBranch("美食")

	tree.OnSelected = func(uid widget.TreeNodeID) {
		lb.SetText(uid)
	}

	//////
	root := ".."
	dirEntry := widget.NewEntry()
	dirEntry.Text = root

	// 创建一个空的tree组件
	tree2 := widget.NewTree(nil, nil, nil, nil)

	// 选择事件
	tree2.OnSelected = func(uid widget.TreeNodeID) {
		lb.SetText(uid)
	}

	// 刷新tree
	dirBtn := widget.NewButton("显示tree", func() {
		refreshTree(tree2, dirEntry.Text)
	})

	c := container.NewBorder(container.NewVBox(
		lb,
		dirEntry,
		dirBtn,
	), nil, tree, nil, tree2)
	myWin.SetContent(c)
	myWin.Resize(fyne.NewSize(550, 450))
	myWin.ShowAndRun()
}

func refreshTree(tree2 *widget.Tree, root string) {
	// 设置根节点
	tree2.Root = root

	// 获取子节点
	tree2.ChildUIDs = func(uid widget.TreeNodeID) (c []widget.TreeNodeID) {
		if uid == "" {
			c = getFiles(root)
		} else {
			c = getFiles(uid)
		}
		return
	}

	// 创建空节点，节点是个Label组件
	tree2.CreateNode = func(branch bool) (o fyne.CanvasObject) {
		return widget.NewLabel("")
	}

	// 给每个节点的Label组件设置文本
	tree2.UpdateNode = func(uid widget.TreeNodeID, branch bool, node fyne.CanvasObject) {
		l := node.(*widget.Label)
		l.SetText(getFileName(uid))
	}

	// 判断是否是分支节点
	tree2.IsBranch = func(uid widget.TreeNodeID) (ok bool) {
		return isDir(uid)
	}
	
	tree2.Refresh()
}

// 获取文件名
func getFileName(path string) string {
	fi, err := os.Stat(path)
	if err != nil {
		return ""
	}
	return fi.Name()
}

// 判断是否是目录节点
func isDir(path string) bool {
	fi, err := os.Stat(path)
	if err != nil {
		return false
	}
	return fi.IsDir()
}

// 获取指定路径下的文件列表
func getFiles(path string) (list []string) {
	fi, err := ioutil.ReadDir(path)
	if err != nil {
		fyne.LogError("open dir err:", err)
		return
	}

	for _, file := range fi {
		filename := path + string(filepath.Separator) + file.Name()
		list = append(list, filename)
	}
	return
}
